import 'package:flutter/material.dart';

/// Dart控制流程示例
class ControlFlowExample extends StatefulWidget {
  const ControlFlowExample({super.key});

  @override
  State<ControlFlowExample> createState() => _ControlFlowExampleState();
}

class _ControlFlowExampleState extends State<ControlFlowExample> {
  String result = '点击下方按钮查看控制流程示例';

  void _demonstrateIfElse() {
    int score = 85;
    String grade;

    if (score >= 90) {
      grade = 'A - 优秀';
    } else if (score >= 80) {
      grade = 'B - 良好';
    } else if (score >= 70) {
      grade = 'C - 中等';
    } else if (score >= 60) {
      grade = 'D - 及格';
    } else {
      grade = 'F - 不及格';
    }

    // 三元运算符
    String status = score >= 60 ? '通过' : '未通过';

    setState(() {
      result = '''
【if-else 条件判断】
分数: $score

if (score >= 90) {
  grade = 'A - 优秀';
} else if (score >= 80) {
  grade = 'B - 良好';
} else if (score >= 70) {
  grade = 'C - 中等';
} else if (score >= 60) {
  grade = 'D - 及格';
} else {
  grade = 'F - 不及格';
}

评级: $grade

三元运算符:
var status = score >= 60 ? '通过' : '未通过';
结果: $status
      ''';
    });
  }

  void _demonstrateForLoop() {
    StringBuffer output = StringBuffer();

    // 传统for循环
    output.writeln('【传统for循环】');
    for (int i = 1; i <= 5; i++) {
      output.writeln('第 $i 次迭代');
    }

    output.writeln('\n【for-in循环】');
    List<String> fruits = ['苹果', '香蕉', '橙子'];
    for (var fruit in fruits) {
      output.writeln('水果: $fruit');
    }

    output.writeln('\n【forEach方法】');
    fruits.forEach((fruit) {
      output.writeln('→ $fruit');
    });

    setState(() {
      result = output.toString();
    });
  }

  void _demonstrateWhileLoop() {
    StringBuffer output = StringBuffer();

    // while循环
    output.writeln('【while循环】');
    int count = 1;
    while (count <= 5) {
      output.writeln('count = $count');
      count++;
    }

    // do-while循环
    output.writeln('\n【do-while循环】');
    int num = 1;
    do {
      output.writeln('num = $num');
      num++;
    } while (num <= 3);

    output.writeln('\n说明: do-while至少执行一次');

    setState(() {
      result = output.toString();
    });
  }

  void _demonstrateSwitchCase() {
    String getDayType(int day) {
      switch (day) {
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
          return '工作日';
        case 6:
        case 7:
          return '周末';
        default:
          return '无效日期';
      }
    }

    setState(() {
      result = '''
【Switch-Case语句】

switch (day) {
  case 1:
  case 2:
  case 3:
  case 4:
  case 5:
    return '工作日';
  case 6:
  case 7:
    return '周末';
  default:
    return '无效日期';
}

示例结果:
第1天: ${getDayType(1)}
第3天: ${getDayType(3)}
第6天: ${getDayType(6)}
第7天: ${getDayType(7)}
      ''';
    });
  }

  void _demonstrateBreakContinue() {
    StringBuffer output = StringBuffer();

    // break示例
    output.writeln('【break - 跳出循环】');
    for (int i = 1; i <= 10; i++) {
      if (i == 6) {
        output.writeln('遇到6，跳出循环');
        break;
      }
      output.writeln('i = $i');
    }

    // continue示例
    output.writeln('\n【continue - 跳过本次迭代】');
    for (int i = 1; i <= 10; i++) {
      if (i % 2 == 0) {
        continue; // 跳过偶数
      }
      output.writeln('奇数: $i');
    }

    setState(() {
      result = output.toString();
    });
  }

  void _demonstrateCollectionIf() {
    bool showExtras = true;
    
    // 集合中的if
    var items = [
      '必需项1',
      '必需项2',
      if (showExtras) '额外项1',
      if (showExtras) '额外项2',
    ];

    // 集合中的for
    var numbers = [
      for (var i = 1; i <= 5; i++) i * 2,
    ];

    setState(() {
      result = '''
【集合中的if/for】

1. 集合中的if:
var items = [
  '必需项1',
  '必需项2',
  if (showExtras) '额外项1',
  if (showExtras) '额外项2',
];

结果: $items

2. 集合中的for:
var numbers = [
  for (var i = 1; i <= 5; i++) i * 2,
];

结果: $numbers
      ''';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Dart 控制流程'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 说明卡片
            Card(
              color: Colors.green.shade50,
              child: const Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '🔄 控制流程概述',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(height: 8),
                    Text(
                      'Dart提供了丰富的控制流程语句：\n'
                      '• 条件判断：if-else, switch-case\n'
                      '• 循环：for, for-in, while, do-while\n'
                      '• 控制：break, continue\n'
                      '• 集合控制流：if和for可用于集合字面量',
                      style: TextStyle(fontSize: 14),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 代码示例区域
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.grey.shade200,
                borderRadius: BorderRadius.circular(8),
              ),
              child: const Text(
                '''// 条件判断
if (condition) {
  // code
} else {
  // code
}

// 循环
for (var i = 0; i < 10; i++) {
  print(i);
}

for (var item in list) {
  print(item);
}

while (condition) {
  // code
}

// 集合控制流
var list = [
  'item1',
  if (condition) 'item2',
  for (var i in items) i,
];''',
                style: TextStyle(
                  fontFamily: 'monospace',
                  fontSize: 13,
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 交互按钮
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                ElevatedButton.icon(
                  onPressed: _demonstrateIfElse,
                  icon: const Icon(Icons.call_split),
                  label: const Text('if-else'),
                ),
                ElevatedButton.icon(
                  onPressed: _demonstrateForLoop,
                  icon: const Icon(Icons.repeat),
                  label: const Text('for循环'),
                ),
                ElevatedButton.icon(
                  onPressed: _demonstrateWhileLoop,
                  icon: const Icon(Icons.loop),
                  label: const Text('while循环'),
                ),
                ElevatedButton.icon(
                  onPressed: _demonstrateSwitchCase,
                  icon: const Icon(Icons.alt_route),
                  label: const Text('switch-case'),
                ),
                ElevatedButton.icon(
                  onPressed: _demonstrateBreakContinue,
                  icon: const Icon(Icons.skip_next),
                  label: const Text('break/continue'),
                ),
                ElevatedButton.icon(
                  onPressed: _demonstrateCollectionIf,
                  icon: const Icon(Icons.collections_bookmark),
                  label: const Text('集合控制流'),
                ),
              ],
            ),
            const SizedBox(height: 16),

            // 结果展示区域
            Card(
              elevation: 4,
              child: Container(
                width: double.infinity,
                padding: const EdgeInsets.all(16),
                constraints: const BoxConstraints(minHeight: 150),
                child: Text(
                  result,
                  style: const TextStyle(
                    fontSize: 14,
                    fontFamily: 'monospace',
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

